package com.example.thirdhomework

import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File

class ForthActivity : AppCompatActivity() {
    private lateinit var resultLauncher: ActivityResultLauncher<Uri>
    private lateinit var photoUri: Uri
    private  lateinit var imageView: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        enableEdgeToEdge()
        setContentView(R.layout.activity_forth)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val button = findViewById<android.widget.Button>(R.id.button)
        imageView = findViewById<android.widget.ImageView>(R.id.imageView)

        resultLauncher = registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
            if (success) {
                val inputStream = contentResolver.openInputStream(photoUri)
                val bitmap = BitmapFactory.decodeStream(inputStream)
                imageView.setImageBitmap(bitmap)
            }
        }

        button.setOnClickListener {
            var photoFile = File.createTempFile("photo", ".jpg", externalCacheDir)
            photoUri = FileProvider.getUriForFile(this, "com.example.thirdhomework.fileprovider", photoFile)
            resultLauncher.launch(photoUri)
        }
    }
}